package indicator

// MACD MACD称为异同移动平均线(移动平均收敛发散指标)
type MACD struct {
	short  *EMA
	long   *EMA
	signal *EMA
	dif    float64
	dea    float64
	macd   float64
}

func NewMACD(short, long, signal int32) *MACD {
	return &MACD{short: NewEMA(short), long: NewEMA(long), signal: NewEMA(signal)}
}

func NewMACD2(short, long, signal *EMA) *MACD {
	return &MACD{short: short, long: long, signal: signal}
}

func (m *MACD) Update(price float64, lastMacd *MACD) (float64, float64, float64) {
	var s, l float64
	if lastMacd == nil {
		s = m.short.Update(price, nil)
		l = m.long.Update(price, nil)
		m.dif = s - l
		// DEA值的计算公式为：当天DEA值=（当天的DIF值×2+昨天的DEA值×8）÷10
		m.dea = m.dif * 2 / (m.signal.n + 1)
	} else {
		s = m.short.Update(price, lastMacd.short)
		l = m.long.Update(price, lastMacd.long)
		m.dif = s - l
		// DEA值的计算公式为：当天DEA值=（当天的DIF值×2+昨天的DEA值×8）÷10
		// 前一日DEA×8/10+今日DIF×2/10。
		// m.dea = (m.dea*(m.signal.n-1) + m.dif*2) / (m.signal.n + 1.0)
		m.dea = m.signal.Update(m.dif, lastMacd.signal)
	}
	m.macd = 2.0 * (m.dif - m.dea)
	return m.dif, m.dea, m.macd
}
func (m *MACD) GetShort() *EMA {
	return m.short
}

func (m *MACD) GetLong() *EMA {
	return m.long
}

func (m *MACD) GetSignal() *EMA {
	return m.signal
}
